//
//  CommonWebController.swift
//  LayerAssistance
//
//  Created by qiuxiankai on 2016/12/23.
//  Copyright © 2020. All rights reserved.
//

import UIKit
import WebKit

class CommonWebController: UIViewController, WKNavigationDelegate, WKUIDelegate {
    
    var commonWebview = WKWebView()
    var reportUrl:String? // 网页路径
    var pathUrl:String? // 本地路径
    var htmlSting:String? // html代码
    var cacheFileName: String? // 本地存储文件名

    /// 是否需要自动编码
    var needEncode = true
    fileprivate lazy var progress: UIProgressView = {
        let progress = UIProgressView()
        progress.frame = CGRect(x: 0, y: 0, width: KSGlobal.screenW, height: 5)
        progress.backgroundColor = #colorLiteral(red: 0.1803921569, green: 0.1960784314, blue: 0.568627451, alpha: 1)
        return progress
    }()
    var isTranslucent_ori:Bool? // 本控件需要操作，但是又不希望影响到其他的控件
    init(needEncode:Bool = true) {
        self.needEncode = needEncode
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
       
        // 防止位置会下移一个导航的高度
        isTranslucent_ori = self.navigationController?.navigationBar.isTranslucent
        self.navigationController?.navigationBar.isTranslucent = false
        
        
        let appdelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
        appdelegate.allowRotation = true
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if let trat = isTranslucent_ori {
            self.navigationController?.navigationBar.isTranslucent = trat
        }
   
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.allowRotation = false //禁止旋转
        UIDevice.current.setValue(1, forKey: "orientation")
        /*KVC的方式设置物理转动的值，用于强制旋转，也就是手机传感器没有检测到手机转动，但给其系统状态赋值成已经是竖屏的状态。
        */
         UIViewController.attemptRotationToDeviceOrientation() //应用刷新视图
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
 
        
        self.view.backgroundColor = .white
        
        let config = WKWebViewConfiguration()
        config.preferences = WKPreferences()
        config.preferences.minimumFontSize = 18
        config.processPool = WKProcessPool()
        let navH = self.navigationController.isSome ? self.navigationController!.navigationBar.frame.height : 0
        let topH = ksStatusbarHeight + navH
        
        commonWebview = WKWebView(frame: CGRect(x:0,y:0,width:KSGlobal.screenW,height:KSGlobal.screenH - topH), configuration: config)
         view.addSubview(commonWebview)
        // 用约束能更好的适配旋转屏
        commonWebview.snp.makeConstraints { (make) in
            make.left.right.top.bottom.equalTo(self.view)
        }
        //进度条
        commonWebview.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        //添加webView
        commonWebview.navigationDelegate = self
        commonWebview.uiDelegate = self
        
        commonWebview.addSubview(progress)
        startShowContent()
     
        
        
    }
    func startShowContent() {
        
        if cacheFileName?.isEmpty != nil {
            
            let fName = cacheFileName!
            if let encodeName = fName.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
                let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
                let fileURL = documentsDirectory.appendingPathComponent("\(encodeName)")
                
                if FileManager.default.fileExists(atPath: fileURL.path) {
                    
                    if cacheFileName!.contains(".mp4") {
                        let videoVC = VideoCachePlayer()
                        videoVC.videoURL = fileURL
                        addChild(videoVC)
                        view.addSubview(videoVC.view)
                        videoVC.view.snp.makeConstraints { make in
                            make.edges.equalTo(UIEdgeInsets.zero)
                        }
                        return
                    } else if cacheFileName!.contains(".pdf") {
                        
                        commonWebview.load(URLRequest(url: fileURL, cachePolicy: .reloadIgnoringLocalCacheData))
                        return
                    }
                }
            }
        }
        
        if let urlstr = reportUrl {
            var dealStr:String = ""
            if  self.needEncode {
                dealStr = urlstr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
            } else {
                dealStr = urlstr
            }
            if let url = URL(string: dealStr) {
                
                // 取视频/文件缓存
                if dealStr.rangeOf(str: ".mp4").length > 0 {
                    // 视频
                    let videoVC = VideoCachePlayer()
                    videoVC.videoURL = url
                    addChild(videoVC)
                    view.addSubview(videoVC.view)
                    videoVC.view.snp.makeConstraints { make in
                        make.edges.equalTo(UIEdgeInsets.zero)
                    }
                    return
                }
                
                // 不缓存
                commonWebview.load(URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData))
            } else {
                KSToast("url有误")
                self.navigationController?.popViewController(animated: true)
            }
        }
        
        if let pUrl = pathUrl {
            let url = URL(fileURLWithPath: pUrl)
            commonWebview.load(URLRequest(url: url))
        }
        if let hStr = htmlSting {
            commonWebview.loadHTMLString(hStr, baseURL: nil)
        }
    }
    
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            print("进度")
            print(commonWebview.estimatedProgress)
            progress.progress = Float(commonWebview.estimatedProgress)
        }
        
        if !commonWebview.isLoading {
            UIView.animate(withDuration: 0.55, animations: { () -> Void in
                self.progress.alpha = 0.0;
            })
        }
        
    }
    
    
    
    
    deinit {
        print("网页显示销毁")
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
}

// MARK: navigationDelegate
extension CommonWebController {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        UIView.animate(withDuration: 0.55, animations: { () -> Void in
            self.progress.alpha = 0.0;
        })
        
        
    }
    
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        print("加载出了点问题")
    }
    
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        print("start")
        
    }
    
    
    
    
    // WKNavigationDelegate 方法，用于拦截请求
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if let url = navigationAction.request.url, url.absoluteString.contains("alipay") || url.absoluteString.contains("weixin") {
            
            if UIApplication.shared.canOpenURL(URL(string: url.absoluteString)!) {
                    // 支付宝已安装，打开支付宝应用
                UIApplication.shared.open(URL(string: url.absoluteString)!)
                    decisionHandler(.cancel) // 取消当前 webView 的加载
                }  else {
                    // 支付宝未安装，处理其他逻辑（例如提示用户安装）
                    print("未安装")
                    decisionHandler(.allow) // 允许当前 webView 的加载
                }
           
        } else {
            // 不包含alipay的URL，正常处理
            decisionHandler(.allow)
        }
    }
    
    

}


func go2ChartForWeb_10(url:String, path:String, title:String, parameters:[AnyHashable : Any], currentVC:UIViewController) {
    
    let cwebV = CommonWebController()
    cwebV.title = title
    var preUrl = "\(url)\(path)"
    var subUrl = ""
    for (key,value) in parameters {
        subUrl = "\(subUrl)&\(key)=\(value)"
    }
    let rUrl = preUrl + subUrl + "&op=h5"
    let rUrl_nowhitespaces = rUrl.removeAllSapce
    
    let encodeStr = rUrl_nowhitespaces.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
    cwebV.reportUrl = encodeStr
    KSLog(encodeStr)
    currentVC.navigationController?.pushViewController(cwebV, animated: true)
}


func go2ChartForWeb(url:String, path:String, title:String, parameters:[AnyHashable : Any], currentVC:UIViewController) {
    
    let cwebV = CommonWebController()
    cwebV.title = title
    var preUrl = ""
    if path.contains("frm") {
        preUrl = "\(url)?formlet=\(path)"
    } else {
        preUrl = "\(url)?reportlet=\(path)"
    }
    var subUrl = ""
    for (key,value) in parameters {
        subUrl = "\(subUrl)&\(key)=\(value)"
    }
    let rUrl = preUrl + subUrl + "&op=h5"
    let rUrl_nowhitespaces = rUrl.removeAllSapce
    
    let encodeStr = rUrl_nowhitespaces.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
    cwebV.reportUrl = encodeStr
    KSLog(encodeStr)
    currentVC.navigationController?.pushViewController(cwebV, animated: true)
}
func go2ChartForWeb_yizhi(url:String, path:String, title:String, parameters:[AnyHashable : Any], currentVC:UIViewController) {
    
    let cwebV = CommonWebController()
    cwebV.title = title
    var preUrl = ""
    if path.contains("frm") {
        preUrl = "\(url)?formlet=\(path)"
    } else {
        preUrl = "\(url)?reportlet=\(path)"
    }
    var subUrl = ""
    for (key,value) in parameters {
        subUrl = "\(subUrl)&\(key)=\(value)"
    }
    let rUrl = preUrl + subUrl + "&op=h5"
    let rUrl_nowhitespaces = rUrl.removeAllSapce
    
    let encodeStr = rUrl_nowhitespaces.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
    cwebV.reportUrl = encodeStr
    currentVC.navigationController?.pushViewController(cwebV, animated: true)
}
